package com.payment.notify.core;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.payment.notify.PaymentAppNotifyApplication;
import com.payment.notify.domain.TblTradeNotifyRecord;
import com.payment.notify.dto.NotifyParam;
import com.payment.notify.enums.NotifyStatusEnum;

/**
 * 类名：NotifyQueue.java<br>
 * 描述：消息队列<br>
 * 创建者：XINJF<br>
 * 创建日期：2018年4月20日下午1:57:56<br>
 * 版本：1.0<br>
 * 修改者：<br>
 * 修改日期：<br>
 */

@Component
public class NotifyQueue implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Logger logger = LoggerFactory.getLogger(NotifyQueue.class);

	@Autowired
	private NotifyParam notifyParam;
	
	@Autowired
	private NotifyPersist notifyPersist;

	/**
	 * 功能描述: 将传过来的对象进行通知次数判断，之后决定是否放在任务队列中 <br>
	 * 创建者：XINJF<br>
	 * 创建日期:2018年4月24日下午2:13:27<br>
	 * 版本：1.0<br>
	 * 修改者：<br>
	 * 修改日期：<br>
	 * @param notifyRecord
	 */
	public void addElementToList(TblTradeNotifyRecord notifyRecord) {
		System.out.println("notifyParam=="+notifyParam);
		if (notifyRecord == null) {
			return;
		}
		Integer notifyTimes = notifyRecord.getNotifyTimes(); // 通知次数
		Integer maxNotifyTime = 0;
		try {
			maxNotifyTime = notifyParam.getMaxNotifyTime();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (notifyRecord.getVersion().intValue() == 0) {// 刚刚接收到的数据
			notifyRecord.setLastNotifyTime(new Date());
		}
		long time = notifyRecord.getLastNotifyTime().getTime();
		Map<Integer, Integer> timeMap = notifyParam.getNotifyParams();
		if (notifyTimes < maxNotifyTime) {
			Integer nextKey = notifyTimes + 1;
			Integer next = timeMap.get(nextKey);
			System.out.println("next=="+next);
			if (next != null) {
				time += 1000 * 60 * next + 1;
				notifyRecord.setLastNotifyTime(new Date(time));
				PaymentAppNotifyApplication.tasks.put(new NotifyTask(notifyRecord, this, notifyParam));
			}
		} else {
			try {
				// 持久化到数据库中
				notifyPersist.updateNotifyRord(notifyRecord.getId(),
						notifyRecord.getNotifyTimes(), NotifyStatusEnum.FAILED.getValue());
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
	}

}
